package com.cn.wanxi.servlet.user;

import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        0.解决乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        1.得到页面数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");//页面的验证码
//        request,session,page,application四个作用域
        String sessionCode = (String) req.getSession().getAttribute("code");//session缓存的验证码
//        如果验证码正确，则进入登陆，否则直接提示验证码错误，请重新输入
        if (code.equals(sessionCode)) {
//        2.封装页面数据
            UserModel userModel = new UserModel();
            userModel.setUsername(username);
            userModel.setPassword(password);

            //        3.调用服务逻辑层
            IUserService iUserService = new UserServiceImpl();
//通过当前拿到的用户名和密码去查询，如果用户名和密码正确，则进入后台管理页面，否则重新登陆
            String result = iUserService.login(userModel);
            if (result.equals("1")) {
                req.getSession().setAttribute("username", username);
                req.getRequestDispatcher("/back/home.jsp").forward(req, resp);
            } else {
                req.setAttribute("result", "用户名或者密码错误，请重新输入");
                req.getRequestDispatcher("/back/login.jsp").forward(req, resp);
            }

        } else {
            req.setAttribute("result", "验证码输入错误，请重新输入验证码");
            req.getRequestDispatcher("/back/login.jsp").forward(req, resp);
        }
    }
}
